package com.sakura.probe.common.exception;

import com.sakura.probe.common.api.CommonResult;
import org.apache.shiro.ShiroException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class JwtException {


    /**捕获与Shiro相关的异常*/
    @ExceptionHandler(ShiroException.class)
    public CommonResult handle401(){
        //您没有权限访问!
        return CommonResult.forbidden(null);
    }


    /**捕获其他异常*/
    @ExceptionHandler(Exception.class)
    public CommonResult globalException(HttpServletRequest request, Throwable e){
        return CommonResult.failed(getStatus(request).value(),
                "访问出错,无法访问："+e.getMessage());
    }

    private HttpStatus getStatus(HttpServletRequest request) {
        Integer statusCode = (Integer) request.getAttribute("java.servlet.error.status_code");
        if (null == statusCode){
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        return HttpStatus.valueOf(statusCode);
    }
}
